import { Component, OnInit } from '@angular/core';
import { FingerprintAIO } from '@ionic-native/fingerprint-aio/ngx';
import { ActionSheetController,LoadingController } from '@ionic/angular';
import { Router,ActivatedRoute,NavigationExtras } from '@angular/router';
import { ToastController } from '@ionic/angular';
import { HttpClient,HttpHeaders } from "@angular/common/http";
import { TranslateService } from '@ngx-translate/core';
import { DefaultLanguageService } from '@services/default-language.service';
import { EncryptService } from '@services/encrypt.service';
import { AuthTokenService } from '@services/auth-token.service';
import { CommonResponse,VerificationType,ToastColor,CommonService } from '@services/common-service.service';

@Component({
  selector: 'app-signin-fingerprint',
  templateUrl: './signin-fingerprint.page.html',
  styleUrls: ['./signin-fingerprint.page.scss'],
})
export class SigninFingerprintPage implements OnInit {


  public appUserId:string;
  public i18n:any;
  public greetings:string;

  constructor(private router: Router,
    private actionSheetController: ActionSheetController,
    private faio:FingerprintAIO,
    private route: ActivatedRoute,
    private http:HttpClient,
    private translate: TranslateService,
    private toastController: ToastController,
    private defaultLanguageService:DefaultLanguageService,
    private encryptService:EncryptService,
    private authTokenService: AuthTokenService,
    private commonService:CommonService,
    public loadingController: LoadingController) {
      this.i18n = this.commonService.initTranslate(['auth.signinFingerprint']); 
      this.getGreetings();
      this.appUserId = this.authTokenService.getAppUserId();
  }

  getGreetings(){
    let date = new Date();
    let hour = date.getHours();
    if(hour>=6 && hour<11){
      this.greetings = "Good morning";
    }else if(hour>=11 && hour<13){
      this.greetings = "Good noon";
    }else if(hour>=13 && hour<18){
      this.greetings = "Good afternoon";
    }else{
      this.greetings = "Good evening";
    }
  }

  ngOnInit() {
  }

  loginWithFingerprint(){
    this.faio.show({
        title: '',
        fallbackButtonTitle: 'Use Backup',
        disableBackup:true,
    }).then((result: any) => {
      if(result == "biometric_success"){
          this.fingerPrintLogin();
      }
    }).catch((error: any) => {
      console.log(error);
      //this.commonService.commonToast(ToastColor.warning,'operate failed');
    });
  }

  async fingerPrintLogin(){
    const loading = await this.loadingController.create({
      cssClass: 'my-custom-class',
      message: 'Please wait...',

    });
    await loading.present();
    var api = "/scm/app/loginWithFingerPrint.do";
    let currentTime = new Date().getTime().toString();
    let appUserId = this.authTokenService.getAppUserId();
    let deviceId = this.authTokenService.getDeviceId();
    let sign1 = this.encryptService.md5Ecrypt(appUserId+deviceId+currentTime);
    let sign2 = this.encryptService.rsaEcrypt(appUserId+","+deviceId+","+currentTime);
    let loginToken = this.authTokenService.getLoginToken();
    const httpOptions = {
      headers: new HttpHeaders({ 'Content-Type': 'application/json','sign1':sign1,'sign2':sign2,'LOGIN_TOKEN':loginToken })
    };
    this.http.post(api,{},httpOptions).subscribe((response:CommonResponse) => {
      if(response.isSuccess){
        this.commonService.commonToast(ToastColor.success,this.i18n.login_success);
        this.authTokenService.login(response);
        this.router.navigate(['/tabs/home']);
      }
      loading.dismiss();
    },(errorResponse)=>{
      this.commonService.errorRespCommonToast(errorResponse,this.i18n);
      loading.dismiss();
    });
  }

  async presentActionSheet() {
    const actionSheet = await this.actionSheetController.create({
      header: '',
      keyboardClose:true,
      buttons: [{
        text: this.i18n.user_password_login,
        role: '',
        icon: '',
        handler: () => {
          this.router.navigate(['/auth/signin-password']);
        }
      },
      {
        text: this.i18n.sms_security_login,
        icon: '',
        handler: () => {
          this.router.navigate(['/auth/signin-sms']);
        }
      }, {
        text: this.i18n.switch_user_signup,
        icon: '',
        handler: () => {
          this.router.navigate(['/auth/signin-first']);
        }
      }, {
        text: this.i18n.cancel,
        icon: '',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();
  }
}
